<!DOCTYPE html>
<html lang="zh-CN">
<head>
  <meta charset="UTF-8">
  <meta name="viewport" content="width=device-width, initial-scale=1.0">
  <title>数据管理系统</title>
  <style>
    body {
      font-family: Arial, sans-serif;
      margin: 0;
      padding: 20px;
      background-color: #f5f5f5;
    }
    .container {
      max-width: 1200px;
      margin: 0 auto;
      background-color: white;
      padding: 20px;
      border-radius: 5px;
      box-shadow: 0 0 10px rgba(0,0,0,0.1);
    }
    h1 {
      text-align: center;
      color: #333;
    }
    .form-group {
      margin-bottom: 15px;
    }
    label {
      display: block;
      margin-bottom: 5px;
      font-weight: bold;
    }
    input[type="text"], input[type="email"], input[type="number"], select {
      width: 100%;
      padding: 8px;
      border: 1px solid #ddd;
      border-radius: 4px;
      box-sizing: border-box;
    }
    button {
      background-color: #4CAF50;
      color: white;
      padding: 10px 15px;
      border: none;
      border-radius: 4px;
      cursor: pointer;
      margin-right: 10px;
    }
    button:hover {
      background-color: #45a049;
    }
    button.delete {
      background-color: #f44336;
    }
    button.delete:hover {
      background-color: #d32f2f;
    }
    button.edit {
      background-color: #2196F3;
    }
    button.edit:hover {
      background-color: #0b7dda;
    }
    table {
      width: 100%;
      border-collapse: collapse;
      margin-top: 20px;
    }
    th, td {
      border: 1px solid #ddd;
      padding: 12px;
      text-align: left;
    }
    th {
      background-color: #f2f2f2;
    }
    tr:nth-child(even) {
      background-color: #f9f9f9;
    }
    tr:hover {
      background-color: #f1f1f1;
    }
    .action-buttons {
      display: flex;
      gap: 5px;
    }
    .search-box {
      margin-bottom: 20px;
    }
    .modal {
      display: none;
      position: fixed;
      z-index: 1;
      left: 0;
      top: 0;
      width: 100%;
      height: 100%;
      overflow: auto;
      background-color: rgba(0,0,0,0.4);
    }
    .modal-content {
      background-color: #fefefe;
      margin: 15% auto;
      padding: 20px;
      border: 1px solid #888;
      width: 80%;
      max-width: 500px;
      border-radius: 5px;
    }
    .close {
      color: #aaa;
      float: right;
      font-size: 28px;
      font-weight: bold;
      cursor: pointer;
    }
    .close:hover {
      color: black;
    }
  </style>
  <script src="js/jquery.min.js" ></script>
</head>
<body>
<div class="container">
  <h1>数据管理系统</h1>

  <!-- 搜索功能 -->
  <div class="search-box">
    <input type="text" id="searchInput" placeholder="输入关键字搜索..." style="width: 300px; padding: 10px;">
    <button onclick="searchData()">搜索</button>
    <button onclick="openAddModel()">添加</button>

  </div>

  <!-- 数据列表 -->
  <h2>数据列表</h2>
  <table id="dataTable">
    <thead>
    <tr>
      <th>ID</th>
      <th>姓名</th>
      <th>邮箱</th>
      <th>年龄</th>
      <th>性别</th>
      <th>操作</th>
    </tr>
    </thead>
    <tbody id="tableBody">
    <!-- 数据将通过JavaScript动态加载 -->
    </tbody>
  </table>
</div>

<div id="addModal" class="modal">
  <!-- 添加数据表单 -->
  <div class="modal-content">
    <span class="close" onclick="closeModal()">&times;</span>
    <h2>添加新数据</h2>
    <div class="form-group">
      <label for="name">姓名:</label>
      <input type="text" id="name" required>
    </div>
    <div class="form-group">
      <label for="email">邮箱:</label>
      <input type="email" id="email" required>
    </div>
    <div class="form-group">
      <label for="age">年龄:</label>
      <input type="number" id="age" min="0" required>
    </div>
    <div class="form-group">
      <label for="gender">性别:</label>
      <select id="gender">
        <option value="男">男</option>
        <option value="女">女</option>
      </select>
    </div>
    <button onclick="addData()">添加</button>
    <button onclick="clearForm()">清空</button>
  </div>
</div>
<!-- 编辑模态框 -->
<div id="editModal" class="modal">
  <div class="modal-content">
    <span class="close" onclick="closeModal()">&times;</span>
    <h2>编辑数据</h2>
    <input type="hidden" id="editId">
    <div class="form-group">
      <label for="editName">姓名:</label>
      <input type="text" id="editName" required>
    </div>
    <div class="form-group">
      <label for="editEmail">邮箱:</label>
      <input type="email" id="editEmail" required>
    </div>
    <div class="form-group">
      <label for="editAge">年龄:</label>
      <input type="number" id="editAge" min="0" required>
    </div>
    <div class="form-group">
      <label for="editGender">性别:</label>
      <select id="editGender">
        <option value="男">男</option>
        <option value="女">女</option>
        <option value="其他">其他</option>
      </select>
    </div>
    <button onclick="updateData()">更新</button>
    <button onclick="closeModal()">取消</button>
  </div>
</div>


<script>
  let userData =[];
  $(document).ready(function() {
     loadTableData();
  })


  function loadTableData(username){
      // Ajax 请求获取用户数据
      $.ajax({
        url: '/user/getUserList',  // 后端API URL
        method: 'GET',
        dataType: 'json',
        data:{
          username:username
        },
        success: function(data) {
          console.log(data); // 调试：查看返回的数据
          // 遍历 JSON 数据
          let userListData='';
          userData =data;
          data.forEach(function(user) {
            userListData +=`<tr><td>${user.id}</td>
                    <td>${user.username}</td>
                    <td>${user.email}</td>
                    <td>${user.provinceId}</td>
                    <td>${user.sex}</td>
                    <td class="action-buttons">
                        <button class="edit" onclick="openEditModal(${user.id})">编辑</button>
                        <button class="delete" onclick="deleteData(${user.id})">删除</button>
                    </td>
                    </tr>`;
             });
          console.log(userListData);
          $('#tableBody').html(userListData);
        },
        error: function(jqXHR, textStatus, errorThrown) {
          console.error("Error fetching data: ", textStatus, errorThrown);
        }
      });

  }

  function openAddModel(){
    document.getElementById('addModal').style.display = 'block';

  }




  // 添加数据
  function addData() {
    const name = document.getElementById('name').value;
    const email = document.getElementById('email').value;
    const age = document.getElementById('age').value;
    const sex = document.getElementById('gender').value;

    if (!name || !email || !age) {
      alert('请填写所有必填字段');
      return;
    }


    const userData = {
      username: name,
      email: email,
      provinceId:age,
      sex:sex
    };

    $.ajax({
      url: '/user/addUser', // 替换为你的后端接口地址
      type: 'post', // 请求类型
      contentType: 'application/json', // 指定请求体格式为 JSON
      data: JSON.stringify(
              userData
      ), // 将 JavaScript 对象转换为 JSON 字符串
      success: function(response) {
        alert("添加成功！");
        document.getElementById('addModal').style.display = 'none';
        console.log('用户数据成功发送:', response);
        loadTableData(); //刷新列表数据
        // 处理成功情况
      },
      error: function(xhr, status, error) {
        console.error('发送用户数据失败:', status, error);
        // 处理错误情况
      }
    });


  }

  // 清空表单
  function clearForm() {
    document.getElementById('name').value = '';
    document.getElementById('email').value = '';
    document.getElementById('age').value = '';
    document.getElementById('gender').value = '男';
  }

  // 删除数据
  function deleteData(id) {
    if (confirm('确定要删除这条数据吗？')) {
      //userData = userData.filter(item => item.id !== id);
      //从数据库删除数据
      $.ajax({
        url: '/user/deleteUser/'+id, // 替换为你的后端接口地址
        type: 'delete', // 请求类型
        data: {
          id:id
        }, // 将 JavaScript 对象转换为 JSON 字符串
        success: function(response) {
          alert("删除成功！");
          loadTableData(); //刷新列表数据
          // 处理成功情况
        },
        error: function(xhr, status, error) {
          console.error('发送用户数据失败:', status, error);
          // 处理错误情况
        }
      });


    }
  }

  // 打开编辑模态框
  function openEditModal(id) {
    const item = userData.find(item => item.id === id);
    if (!item) return;

    document.getElementById('editId').value = item.id;
    document.getElementById('editName').value = item.username;
    document.getElementById('editEmail').value = item.email;
    document.getElementById('editAge').value = item.provinceId;
    document.getElementById('editGender').value = item.sex;

    document.getElementById('editModal').style.display = 'block';
  }

  // 关闭模态框
  function closeModal() {
    document.getElementById('editModal').style.display = 'none';
    document.getElementById('addModal').style.display = 'none';
  }

  // 更新数据
  function updateData() {
    const id = parseInt(document.getElementById('editId').value);
    const name = document.getElementById('editName').value;
    const email = document.getElementById('editEmail').value;
    const age = document.getElementById('editAge').value;
    const sex = document.getElementById('editGender').value;

    if (!name || !email || !age) {
      alert('请填写所有必填字段');
      return;
    }
    //更新数据库
    const userData = {
      username: name,
      email: email,
      provinceId:age,
      sex:sex,
      id:id
    };
    $.ajax({
      url: '/user/updateUser', // 替换为你的后端接口地址
      type: 'put', // 请求类型
      contentType: 'application/json', // 指定请求体格式为 JSON
      data: JSON.stringify(
              userData
      ), // 将 JavaScript 对象转换为 JSON 字符串
      success: function(response) {
        alert("修改成功！");
        document.getElementById('editModal').style.display = 'none';
        loadTableData(); //刷新列表数据
        // 处理成功情况
      },
      error: function(xhr, status, error) {
        console.error('发送用户数据失败:', status, error);
        // 处理错误情况
      }
    });



  }

  // 搜索数据
  function searchData() {
    const keyword = document.getElementById('searchInput').value;
    loadTableData(keyword);

  }

  // 点击模态框外部关闭模态框
  window.onclick = function(event) {
    const modal = document.getElementById('editModal');
    if (event.target === modal) {
      closeModal();
    }
  }
</script>
</body>
</html>